<?php
namespace app\middleware;

use Closure;
use thans\jwt\exception\JWTException;
use think\Response;
use think\exception\HttpResponseException;
use thans\jwt\facade\JWTAuth;
/**
 * @author yanxusheng <[<ausheng@foxmail.com>]>
 * @datetime 2023/3/17 16:28
 * @content
 */
class BeforeUsers
{
    public function handle($request, Closure $next)
    {
        // 添加中间件执行代码
        $payload = '';
        try {
            $payload = JWTAuth::auth();
        } catch (JWTException $e) {
            $this->prevent('This request rejected ['.$e->getMessage().'].', 999);
        }

        // 没有问题 请求注入
        $request->usersId = $payload['id']->getValue();
        $request->usersCode = $payload['player_code']->getValue();
        // $request->usersId = 1;
        // $request->usersCode = '7D48444B-7ECA-46A1-A8FC-6BF96DA4E186';

        return $next($request);
    }



    /**
     * @param string $msg
     * @param int $code
     */
    protected function prevent(string $msg, int $code)
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => time(),
            'data' => null,
            'VERSION' => env('app.app_version', '1.0.0'),
        ];

        $response = Response::create($result, 'json', $code)->header();

        throw new HttpResponseException($response);
    }
}